<template>
  <div class="config-wrap" v-if="configShow">
    <div class="right-head">
      <p>节点配置</p>
      <i class="el-icon-close" @click="close"></i>
    </div>
    <div class="right-content">
      <el-form ref="ruleRef" :model="ruleForm" :rules="rules" :label-position="labelPosition" label-width="100px"
        class="demo-ruleForm" size="small">
        <div class="right-basicInfo info-box">
          <p class="basic-info" @click="basicShow = !basicShow">
            <i v-if="basicShow" class="el-icon-caret-bottom"></i>
            <i v-else class="el-icon-caret-top"></i>
            <span>基本信息</span>
          </p>
          <div v-show="basicShow">
            <el-form-item label="引擎名称:" prop="">
              <div class="name">{{ ruleForm.name }}</div>
            </el-form-item>
            <el-form-item label="描述:" prop="">
              <div class="name">{{ ruleForm.description }}</div>
            </el-form-item>
          </div>
        </div>
        <div class="right-basicInfo">
          <p class="basic-info" @click="inputShow = !inputShow">
            <i v-if="inputShow" class="el-icon-caret-bottom"></i>
            <i v-else class="el-icon-caret-top"></i>
            <span>输入参数</span>
          </p>
          <template v-if="ruleForm.inputPreConfig.content">
            <div v-show="inputShow" class="search-table">
              <el-table :data="ruleForm.inputPreConfig.content" style="width: 100%">
                <el-table-column label="参数名称" prop="name">
                </el-table-column>
                <el-table-column label="关键词类型" prop="keywordType">

                  <template v-slot:default="scope">
                    <span>{{ keywordType[scope.row.keywordType] }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="过滤条件" prop="attributes">
                  <template v-slot:default="scope">
                    <span v-if="scope.row.attributes">{{
                      scope.row.attributes.filter
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="描述" prop="desc" width="100">
                  <template v-slot:default="scope">
                    <el-tooltip class="item" effect="dark" :content="scope.row.desc" placement="bottom">
                      <div class="tooltip-box">{{ scope.row.desc }}</div>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </div>
        <div class="right-basicInfo">
          <p class="basic-info" @click="outputShow = !outputShow">
            <i v-if="outputShow" class="el-icon-caret-bottom"></i>
            <i v-else class="el-icon-caret-top"></i>
            <span>输出参数</span>
          </p>
          <template v-if="ruleForm.outputReaderConfig.length">
            <div v-show="outputShow" class="search-table">
              <el-table :data="ruleForm.outputReaderConfig[0].content" style="width: 100%">
                <el-table-column label="参数名称" prop="name">
                </el-table-column>
                <el-table-column label="关键词类型" prop="keywordType">
                  <template v-slot:default="scope">
                    <span>{{ keywordType[scope.row.keywordType] }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="过滤条件" prop="attributes">
                  <template v-slot:default="scope">
                    <span v-if="scope.row.attributes">{{
                      scope.row.attributes.filter
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="描述" prop="desc" width="100">
                  <template v-slot:default="scope">
                    <el-tooltip class="item" effect="dark" :content="scope.row.desc" placement="bottom">
                      <div class="tooltip-box">{{ scope.row.desc }}</div>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </div>
        <div class="right-basicInfo">
          <p class="basic-info" @click="paramsShow = !paramsShow">
            <i v-if="paramsShow" class="el-icon-caret-bottom"></i>
            <i v-else class="el-icon-caret-top"></i>
            <span>执行参数配置</span>
          </p>
          <div class="basic-content" v-show="paramsShow">
            <div class="params-content" v-for="(item, index) in ruleForm.dynamicFieldAndValue" :key="index">
              <template v-if="
                item.componentConfig.componentType === 'input' &&
                item.componentConfig.show
              ">
                <el-form-item :label="item.name" prop="" :required="item.componentConfig.required">
                  <el-input v-model="item.value" :placeholder="`请填写${item.name}`" :disabled="isDetail"></el-input>
                </el-form-item>
              </template>
              <template v-if="
                item.componentConfig.componentType === 'switch' &&
                item.componentConfig.show
              ">
                <el-form-item :label="item.name" prop="" :required="item.componentConfig.required">
                  <el-switch v-model="item.value" :disabled="isDetail" @change="switchChange($event, item)">
                  </el-switch>
                  <el-form-item label="" prop="" v-if="item.child">
                    <div class="child-box" v-for="(leve1, index1) in item.child" :key="index1">
                      <template v-if="leve1.componentConfig.componentType === 'button'">
                        <el-form-item label="" prop="" :required="leve1.componentConfig.required">
                          <div v-if="item.value">
                            <el-button type="primary" size="mini" @click="selectPoc">
                              选择POC
                            </el-button>
                            <span> 已选择 {{ pocNum }} 个POC </span>
                          </div>
                        </el-form-item>
                      </template>
                    </div>
                  </el-form-item>
                </el-form-item>
              </template>
              <template v-if="
                item.componentConfig.componentType === 'select' &&
                item.componentConfig.show
              ">
                <el-form-item :label="item.name" prop="" :required="item.componentConfig.required">
                  <el-select v-model="item.value" :multiple="item.componentConfig.multiple" placeholder="请选择"
                    :popper-append-to-body="false" :disabled="isDetail">
                    <el-option v-for="option in item.componentConfig.dic" :key="option.value" :label="option.label"
                      :value="option.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>

              <template v-if="
                item.componentConfig.componentType === 'object' &&
                item.componentConfig.show
              ">
                <el-form-item :label="item.name" prop="" v-if="item.child">
                  <div class="child-box" v-for="(leve1, index1) in item.child" :key="index1">
                    <template v-if="leve1.componentConfig.componentType === 'input'">
                      <el-form-item :label="leve1.name" prop="" :required="leve1.componentConfig.required">
                        <el-input v-model="leve1.value" :placeholder="`请填写${leve1.name}`"
                          :disabled="isDetail"></el-input>
                      </el-form-item>
                    </template>
                    <template v-if="leve1.componentConfig.componentType === 'select'">
                      <el-form-item :label="leve1.name" prop="" :required="leve1.componentConfig.required">
                        <el-select v-model="leve1.value" :multiple="leve1.componentConfig.multiple" placeholder="请选择"
                          :popper-append-to-body="false" :disabled="isDetail">
                          <el-option v-for="option in leve1.componentConfig.dic" :key="option.value"
                            :label="option.label" :value="option.value">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </div>
                </el-form-item>
              </template>

              <template v-if="
                item.componentConfig.componentType === 'array' &&
                item.componentConfig.show
              ">
                <el-form-item :label="item.name" prop="" v-if="item.child">
                  <div class="child-box" v-for="(leve1, index1) in item.child" :key="index1">
                    <template v-if="leve1.componentConfig.componentType === 'input'">
                      <el-form-item :label="leve1.name" prop="" :required="leve1.componentConfig.required">
                        <div class="array-item">
                          <el-input v-model="leve1.value" :placeholder="`请填写内容`" :disabled="isDetail"></el-input>

                          <i v-if="item.child.length > 1" class="el-icon-minus" @click="delClick(leve1, index)"></i>
                          <i class="el-icon-plus" @click="addClick(item, index)"></i>
                        </div>
                      </el-form-item>
                    </template>
                  </div>
                </el-form-item>
              </template>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <div class="right-footer">
      <el-button class="cancel" size="small" @click="close">取 消</el-button>
      <el-button v-if="!isDetail" class="sure" size="small" type="primary" @click="saveStrategy(ruleRef)">保
        存</el-button>
    </div>

    <!-- 选择POC -->
    <PocSelect v-if="pocShow" :is-show.sync="pocShow" :selectedIds="pocIds" @confirm="confirm"></PocSelect>
  </div>
</template>
<script lang="ts" setup>
  import PocSelect from '@/components/Expose/PocSelect.vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import {defineProps,defineEmits,computed,watch,ref,reactive,inject} from 'vue';
  import {ElMessage} from 'element-plus';
  import {useStore} from 'vuex';
  import {useRoute} from 'vue-router';
  import tools from '@/plugins/common' 
  const store =useStore()
  const route=useRoute();
  const props= defineProps({
    getGraphData:{
      type: Function
    },
    nodeData: {
      type: Object,
      default: () => {
        return {}
      },
    },
    graphData: {
      type: Array,
      default: () => {
        return []
      },
    },
    // 保存类型
    saveType: {
      type: String,
      default: () => {
        return 'strategy'
      },
    },
  })
  const configShow=ref(false);
  const basicShow=ref(true);
  const inputShow=ref(true);
  const outputShow=ref(true);
  const paramsShow=ref(true);
  const labelPosition=ref('top');
  let ruleForm=reactive<any>({
         id: '',
        name: '',
        outputReaderConfig: {
          outputReaderType: '',
          content: [],
        },
        runnerType: 'runnerTask',
        dynamicFieldAndValue: [],
  });
  const rules=reactive({
    engineAccount: [
          { required: true, message: '请填写内容', trigger: 'blur' },
          { max: 100, message: '最多填写100个字符', trigger: 'blur' },
        ],
        apiKey: [
          { required: true, message: '请填写API KEY', trigger: 'blur' },
          { max: 100, message: '最多填写100个字符', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请填写描述', trigger: 'blur' },
        ],
  });
  const keywordType=reactive({
    1: 'IP',
        2: '域名',
        3: '企业名称',
        4: 'URL',
        5: 'IPPort',
        6: '业务关键词',
        7: '自定义查询语法',
        8: '根域名',
  });
  const ruleRef = ref<FormInstance>();
  const pocShow=ref(true);
  const pocIds=ref([]);
  const isSelectPoc=ref(false);
    const nodeId=computed(()=>{
      return props.nodeData.id
    })
    const isDetail=computed(()=>{
      if (
        route.path === '/taskCenter/taskStrategy/strategyDetails' ||
        route.path === '/taskCenter/taskPlan/planDetails'
      ) {
        return true
      } else {
        return false
      }
    })
    const pocNum=computed(()=>{
      return pocIds.value.length
    })
  watch(()=>props.nodeData,(newVal) =>{
    if (newVal) {
          configShow.value = true
          ruleForm = newVal.store.data.data.engine
          ruleForm.dynamicFieldAndValue.forEach((el) => {
            if (el.code === 'inputNodeOutput') {
              el.componentConfig.dic = setFilterData(newVal.id)
              const valueList = el.componentConfig.dic.map((item) => item.value)
              if (el.value && el.value.length > 0) {
                el.value.forEach((item2, index2) => {
                  if (!valueList.includes(item2)) {
                    el.value.splice(index2, 1)
                  }
                })
              }
            }

            // 选择poc回显
            if (el.code === 'isSelectPoc') {
              isSelectPoc.value = el.value;
              if (el.child && el.child.length > 0) {
                el.child.forEach((item2, index2) => {
                  if (item2.value) {
                    pocIds.value = item2.value.split(',')
                  } else {
                    pocIds.value = []
                  }
                })
              }
            }
          })

          ruleForm.dynamicFieldAndValue = tools.convertDataFormat(
            ruleForm.dynamicFieldAndValue,
            'render'
          )
        }
  })
 const close =()=> {
      configShow.value = false
    }
   const confirm= (ids)=> {
      pocIds.value = ids
    }
   const selectPoc= ()=> {
      pocShow.value = true
    }
    // 组装过滤器数据
   
   const setFilterData= (id)=> {
      let arr:any = []
      const graphData: any = props.getGraphData?.();
      const targetEdge = graphData.filter((el) => el?.target?.cell === id) // target 连线数组
      const sourceNodeIds = targetEdge.map((el) => el.source.cell) // 源节点数据ID
      graphData.forEach((el) => {
        if (sourceNodeIds.includes(el.id)) {
          if (el.data.engine.outputReaderConfig.length) {
            let outputReaderConfig =
              el.data.engine.outputReaderConfig[0].content // 上一个节点的输出参数
            outputReaderConfig.forEach((item) => {
              let label = ''
              let filter = ''
              if (item?.attributes?.filter) {
                filter = item.attributes.filter
              }
              if (filter) {
                label = `${keywordType[item.keywordType]}（${filter}）`
              } else {
                label = `${keywordType[item.keywordType]}`
              }
              arr.push({
                label: label,
                value: JSON.stringify(item),
              })
            })
          }
        }
      })

      // 去重
      let newArrId:any[] = []
      let newArrObj:any[] = []
      arr.forEach((item:any) => {
        if (!newArrId.includes(item.label)) {
          newArrId.push(item.label)
          newArrObj.push(item)
        }
      })
      return newArrObj
    }
   const keywordTypeFn= (item)=> {
      let str = ''
      let name = ''
      if (item?.attributes?.filter) {
        name = item.attributes.filter
      }
      if (name) {
        if (keywordType[item.keywordType] == name) {
          str = `${keywordType[item.keywordType]}`
        } else {
          str = `${name}:${keywordType[item.keywordType]}`
        }
      } else {
        str = `${keywordType[item.keywordType]}`
      }
      return str
    }
    // 保存整个画布
   const saveStrategy=  (formEl: FormInstance | undefined)=> {
    if (!formEl) return;
      if (isSelectPoc.value) {
        if (!pocIds.value.length) {
          ElMessage.error('至少选择一个poc！')
          return
        }
      }

      if (props.saveType === 'strategy') {
        ruleForm.dynamicFieldAndValue = tools.convertDataFormat(
          ruleForm.dynamicFieldAndValue,
          'save'
        )

        // 选择poc组装数据
        ruleForm.dynamicFieldAndValue.forEach((el) => {
          if (el.code === 'isSelectPoc') {
            if (el.child && el.child.length > 0) {
              el.child.forEach((item2, index2) => {
                item2.value = pocIds.value.join(',')
              })
            }
          }
        })

        const { strategyName, strategyDesc, strategyType, id } =
          store.state.taskStrategy.strategyInfo

        let strategyConfig :any= inject('getGraphData')
        for (let i = 0; i < strategyConfig.length; i++) {
          if (strategyConfig[i].id === nodeId.value) {
            strategyConfig[i].data.engine = ruleForm
          }
        }

         formEl.validate(async(valid, fields) => {
          if (valid) {
            const params = {
              strategyName: strategyName,
              strategyDesc: strategyDesc,
              strategyType: strategyType,
              strategyConfig: JSON.stringify(strategyConfig),
              id: id,
            }
            const {
              code,
              data = {},
              message,
            } = await store.dispatch('taskStrategy/saveStrategy', params)
            if (code !== 0) {
              ElMessage.error(message)
              return
            }
            close()
          } else {
            return false
          }
        })
      } else {
        ruleForm.dynamicFieldAndValue = tools.convertDataFormat(
          ruleForm.dynamicFieldAndValue,
          'save'
        )

        // 选择poc组装数据
        ruleForm.dynamicFieldAndValue.forEach((el) => {
          if (el.code === 'isSelectPoc') {
            if (el.child && el.child.length > 0) {
              el.child.forEach((item2, index2) => {
                item2.value = pocIds.value.join(',')
              })
            }
          }
        })

        let strategyConfig : any= props.getGraphData?.()
        
        for (let i = 0; i < strategyConfig.length; i++) {
          if (strategyConfig[i].id === nodeId.value) {
            strategyConfig[i].data.engine = ruleForm
          }
        }

        close()
        // console.log(ruleForm, 'this.ruleForm')
      }
    }
   const addClick= (item, index)=> {
    ruleForm.dynamicFieldAndValue[index].child.push({
        type: 'string',
        componentConfig: {
          componentType: 'input',
          required: false,
          show: true,
        },
      })
    }
   const delClick= (item, index)=> {
      ruleForm.dynamicFieldAndValue[index].child.splice(
        ruleForm.dynamicFieldAndValue[index].child.indexOf(item),
        1
      )
    }
    // poc开关
   const switchChange= (val, item)=> {
      // console.log(val, item)
      if (item.code === 'isSelectPoc') {
        isSelectPoc.value = val
      }
    }
</script>
<style lang="scss" scoped>
.config-wrap {
  width: 550px;
  // padding: 20px 36px;
  background: $-white;
  // height: calc(100vh - 235px);
  height: 100%;

  .right-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
    border-bottom: 1px solid rgb(50, 54, 67);

    p {
      font-family: PingFangSC-Medium;
      font-size: 16px;
      font-weight: normal;
      line-height: 22px;
      letter-spacing: 0px;
      // color: rgba(255, 255, 255, 0.9);
    }

    i {
      width: 12px;
      height: 12px;
      cursor: pointer;
      // color: rgba(255, 255, 255, 0.9);
    }
  }

  .right-content {
    height: calc(100% - 110px);
    overflow-y: auto;
  }

  .right-basicInfo {
    padding: 20px 12px;
    margin: 12px;
    border-radius: 8px;
    opacity: 1;

    // background: rgba(49, 52, 65, 0.5);
    .basic-info {
      font-family: PingFang SC;
      font-size: 14px;
      font-weight: normal;
      // color: #ffffff;
      cursor: pointer;

      i {
        font-size: 10px;
        color: #8d93a2;
      }
    }

    .basic-content {
      .child-box {
        padding-left: 30px;

        .array-item {
          display: flex;
          align-items: center;

          i {
            font-size: 14px;
            cursor: pointer;
            margin-left: 8px;
          }

          .el-icon-minus {
            color: #ff4c4c;
          }

          .el-icon-plus {
            color: #0289f7;
          }
        }
      }
    }

    .search-table {
      .tooltip-box {
        max-width: 100px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    >ul {
      display: flex;
      align-items: center;
      flex-flow: wrap;
      gap: 8px;
      margin-top: 10px;

      li {
        display: flex;
        align-items: center;
        background: rgba(58, 206, 255, 0.1);
        border: 0.5px solid rgba(58, 206, 255, 0.6);
        border-radius: 4px;
        height: 26px;
        color: rgb(58, 206, 255);
        font-size: 12px;
        padding: 0px 12px;
      }
    }

    .name {
      font-family: PingFangSC-Medium;
      font-size: 14px;
      font-weight: normal;
      line-height: 40px;
      letter-spacing: 0em;
      // color: rgba(255, 255, 255, 0.9);
    }

    ::v-deep .el-form-item--small.el-form-item {
      margin-bottom: 10px;
    }

    .apiClass {
      ::v-deep .el-form-item__label {
        width: 100%;
        text-align: left;
      }

      .updateClass {
        font-family: PingFangSC-Regular;
        font-size: 12px;
        font-weight: normal;
        line-height: 20px;
        color: #3a7dff;
      }
    }
  }

  .right-footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
    height: 55px;
    border-top: 1px solid rgb(50, 54, 67);
    // padding: 18px;
    position: absolute;
    bottom: 0px;
    right: 0;

    .sure {
      background: #0289f7;
    }
  }
}
</style>
